package com.dhn.newtask;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.dhn.newtask.util.RequestManager;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
    RequestQueue mRequestQueue;
    WebView mWebView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();

    }

    //初始化控件
    void initView() {
        mWebView = (WebView) findViewById(R.id.login_webview);
    }

    //初始化数据
    private void initData() {
        mWebView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                String code = null;
                //如果一回调url开头，则获取code
                if (url.startsWith(Constant.REDIRECT_URL)) {
                    code = extractCode(url);

                    if (!TextUtils.isEmpty(code)) {
                        //从url获取token
                        requestForAccessToken(code);
                    } else {
                        Toast.makeText(MainActivity.this, "出错啦，code为空", Toast.LENGTH_SHORT).show();
                    }

                    //忽略发送从定向url的请求
                    return true;
                }

                return false;

            }
        });


        //请求登录页
        mWebView.loadUrl(Constant.LOGIN_URL);
    }

    private void requestForAccessToken(String code) {
        final JSONObject requestJson = new JSONObject();
        try {
            requestJson.put("client_id", Constant.CLIENT_ID);
            requestJson.put("client_secret", Constant.CLIENT_SECRET);
            requestJson.put("grant_type", "authorization_code");
            requestJson.put("redirect_uri", Constant.REDIRECT_URL);
            requestJson.put("code", code);
            requestJson.put("dataType", "json");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //构造Request
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                Request.Method.POST,
                Constant.TOKEN_URL,
                requestJson,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {
                            //从json数据中提取token
                            String accessToken = (String) response.get("access_token");
                            Constant.Stoken = accessToken;

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        Toast.makeText(MainActivity.this, "授权成功", Toast.LENGTH_LONG).show();
                        CookieManager.getInstance().removeAllCookie();

                        //跳转到主页面
                        onCompleteAuth();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, "出错啦，获取token失败", Toast.LENGTH_SHORT).show();
                    }
                });

        //发送请求
        RequestManager.newInstance(getApplicationContext()).add(jsonObjectRequest);


    }

    //跳转到主页面
    private void onCompleteAuth() {
        //跳转到主页
        Intent intent = new Intent(getApplicationContext(), TweetActivity.class);
        startActivity(intent);

    }


    //从url中提取code
    private String extractCode(String url) {
        int startIndex = url.indexOf("code=") + "code=".length();
        int endIndex = url.indexOf("&state");
        String code = url.substring(startIndex, endIndex);
        return code;
    }
}
